﻿<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="../../Scripts/jquery-1.11.0.min.js" type="text/javascript"></script>
    <script language="JavaScript" src="../../Comm/JScript.js" type="text/javascript"></script>
    <script type="text/javascript" src="../../Scripts/QueryString.js"></script>
    <script type="text/javascript" src="../../Scripts/config.js"></script>
    <script type="text/javascript" src="../../Comm/Gener.js"></script>

    <script src="../../Scripts/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
    <link href="../../Scripts/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <link href="../../Scripts/bootstrap/css/font-awesome.css" rel="stylesheet" type="text/css" />

    <script src="../../Scripts/bootstrap/bootstrap-table/src/bootstrap-table.js" type="text/javascript"></script>
    <link href="../../Scripts/bootstrap/bootstrap-table/src/bootstrap-table.css" rel="stylesheet" type="text/css" />
    <script src="../../Scripts/bootstrap/bootstrap-table/src/locale/bootstrap-table-zh-CN.js" type="text/javascript"></script>

    <script src="../../Scripts/bootstrap/bootstrap-treeview/src/js/bootstrap-treeview.js" type="text/javascript"></script>
    <link href="../../Scripts/bootstrap/bootstrap-treeview/src/css/bootstrap-treeview.css" rel="stylesheet" type="text/css" />
    <!-- 引入用户要重写的公共js -->


    <style type="text/css">
        .row-margin-top {
            margin-top: 20px;
        }

        .search-margin {
            margin-top: 15px;
        }
    </style>
    <script type="text/javascript">
        var mapExt = null;
        function findChildren(jsonArray, parentNo) {
            var appendToTree = function (treeToAppend, child) {
                $.each(treeToAppend, function (i, o) {
                    if (o.id == child.ParentNo) {
                        var checked = false;
                        var selectedNodes = window.selectedNodes;

                        var sel = $.grep(selectedNodes, function (obj) {
                            return child.No == obj.No;
                        });
                        if (sel.length > 0) {
                            checked = true;
                        }
                        o.nodes.push({
                            "id": child.No,
                            "text": child.Name,
                            "nodes": [],
                            "state": { checked: checked}
                        });
                    } else {
                        appendToTree(o.nodes, child);
                    }
                });
            };

            var jsonTree = [];
            if ($.isArray(jsonArray) && typeof parentNo !== "undefined") {
                //如果parentNo不为0，则增加parentNo的部门数据
                if (parentNo != 0) {
                    $.each(jsonArray, function (i, item) {
                        if (item.No == parentNo) {
                            jsonTree.push({
                                "id": parentNo,
                                "text": item.Name,
                                "nodes": []
                            });
                            return;
                        }
                    });
                }
                $.each(jsonArray, function (i, o) {
                    if (o.ParentNo == parentNo) {
                        var checked = false;
                        var selectedNodes = window.selectedNodes;
                        var sel = $.grep(selectedNodes, function (obj) {
                            return o.No == obj.No;
                        });
                        if (sel.length > 0) {
                            checked = true;
                        }
                        jsonTree.push({
                            "id": o.No,
                            "text": o.Name,
                            "nodes": [],
                            "state": { checked: checked }
                        });
                    } else {
                        appendToTree(jsonTree, o);
                    }
                });
            }

            function _(treeArray) {
                $.each(treeArray, function (i, o) {
                    if ($.isArray(o.nodes)) {
                        if (o.nodes.length == 0) {
                            //o.nodes = undefined;
                        } else {
                            _(o.nodes);
                        }
                    }
                });
            }
            _(jsonTree);
            return jsonTree;
        }

        function loadTree(treeUrl, rootNo, global) {
             var json = null;
            if (global.dbType == 0) {
                json = GetDataTableByField("Tag2", rootNo);
            } else 
                json = DBAccess.RunDBSrc(treeUrl, global.dbType, mapExt.FK_DBSrc); //执行url返回json.

            var jsonTree = findChildren(json, rootNo);
            $('#tree').treeview({
                data: jsonTree,         // 数据源
                showCheckbox: mapExt.ShowCheckBox,   //是否显示复选框
                highlightSelected: true,    //是否高亮选中.
                //nodeIcon: 'glyphicon glyphicon-user',    //节点上的图标
                nodeIcon: 'glyphicon',
                emptyIcon: '',    //没有子节点的节点图标
                multiSelect: false,    //多选
                onNodeChecked: function (event, data) {
                    
                },
                nodeUnchecked: function (event, node) {
                },
                onNodeSelected: function (event, node) {
                    var tree = $('#tree');
                    if (node.state.expanded) {
                        //处于展开状态则折叠
                        tree.treeview('collapseNode', node.nodeId);
                    } else {
                        //展开
                        tree.treeview('expandNode', node.nodeId);
                    }
                },
                onNodeExpanded: function (event, data) {
                    var url = global.TreeUrl+"";
                    if (url.toLowerCase().indexOf("@key") != -1) {
                        var json;
                        if (global.dbType == 0) {
                            json = GetDataTableByField("Tag2", data.id);
                        } else {
                            var url = global.TreeUrl.replace("@Key", data.id);
                            url = url.replace("@key", data.id);
                            url = url.replace("@KEY", data.id);
                            json = DBAccess.RunDBSrc(url, global.dbType, mapExt.FK_DBSrc);
                        }
                        var jsonTree = findChildren(json, data.id, global.lazyLoad);
                        $("#tree").treeview("deleteChildrenNode", data.nodeId);	//删除当前节点下的所有子节点

                        $("#tree").treeview("addNode", [data.nodeId, { node: jsonTree, silent: true }]);


                    }
                }
            });
        }

        //查询列表
        function loadViewGrid(gridUrl, keyWord) {
            var global = window;
            var columns = mapExt.Tag;
            var searchTableColumns = [{
                field: "_checkbox",
                checkbox: true,
                formatter: function (value, row, index) {
                    if (row.checked) {
                        return {
                            "checked": true,
                            "disabled": row.disabled
                        }
                    }
                }
            }];

            //显示列的中文名称.
            if (typeof columns == "string") {
                $.each(columns.split(","), function (i, o) {
                    var exp = o.split("=");
                    var field;
                    var title;
                    if (exp.length == 1) {
                        field = title = exp[0];
                    } else if (exp.length == 2) {
                        field = exp[0];
                        title = exp[1];
                    }
                    if (!isLegalName(field)) {
                        return true;
                    }
                    searchTableColumns.push({
                        field: field,
                        title: title
                    });
                });
            } else {
                // by default
                searchTableColumns.push({
                    field: 'No',
                    title: '编号'
                });
                searchTableColumns.push({
                    field: 'Name',
                    title: '名称'
                });
            }
            // grid
            $('#viewGrid').bootstrapTable({
                cache: false,
                minimumCountColumns: 2,
                clickToSelect: true,
                sortable: false,
                maintainSelected: true,
                singleSelect: !mapExt.ShowCheckBox,
                uniqueId: "No",
                columns: searchTableColumns
            });
            var json;
            if (global.dbType == 0) {
                json = GetDataTableByField("Tag1", keyWord);
            } else {
                gridUrl = replaceAll(gridUrl, "@Key", keyWord);
                gridUrl = replaceAll(gridUrl, "@key", keyWord);
                gridUrl = replaceAll(gridUrl, "@KEY", keyWord);
                json = DBAccess.RunDBSrc(gridUrl);
            }

            if ($.isArray(json)) {
                $('#tree_Panel').hide();
                $('#viewGrid_Panel').show();
                var selectedRows = window.selectedNodes;
                if ($.isArray(selectedRows)) {
                    $.each(json, function (i, o) {
                        var sel = $.grep(selectedRows, function (obj) {
                            return o.No == obj.No;
                        });
                        if (sel.length > 0) {
                            o.checked = true;
                            //多选时才需要禁用已选
                            if (mapExt.ShowCheckBox == true) {
                                o.disabled = true;
                            }
                        }
                    });
                }
                $('#viewGrid').bootstrapTable("load", json);
            }
        }

        function isLegalName(name) {
            if (!name) {
                return false;
            }
            return name.match(/^[a-zA-Z\$_][a-zA-Z\d\$_]*$/);
        }

        var global = window;
        var atParas = "";
        $(function () {
            // global
            global.selectedNodes = [];
            global.selectedRows = [];

            var mypk = GetQueryString("MyPK");
            atParas = GetQueryString("AtParas");

            mapExt = new Entity("BP.Sys.MapExt", mypk);
            global.dbType = mapExt.DBType;

            var webUser = new WebUser();
            var tip = mapExt.GetPara("SearchTip");
            var selectType = mapExt.GetPara("SelectType");
            $("#TB_Key").attr("placeholder", tip); //设置查询提示.

            mapExt.ShowCheckBox = selectType == "0" ? false : true;

            //跟节点编号.
            var rootNo = mapExt.Doc;
            if (rootNo == "@WebUser.FK_Dept") {
                rootNo = webUser.FK_Dept;
            }
            if (rootNo == "@WebUser.OrgNo") {
                rootNo = webUser.OrgNo;
            }
            if (rootNo == null || rootNo == undefined) {
                rootNo = "0"
            }

            //设置变量.
            global.FK_MapData = mapExt.FK_MapData;
            global.AttrOfOper = mapExt.AttrOfOper;
            global.oid = GetQueryString("OID");

            var treeUrl = mapExt.Tag2.replace(/~/g, "'");
            var treeTag1 = mapExt.Tag1;
            if (atParas && atParas.indexOf('@') == 0) {
                var paras = atParas.split('@');
                for (i = 0, len = paras.length; i < len; i++) {
                    var key = paras[i];
                    if (key == "" || key == null) {
                        continue;
                    }
                    var attrKeyOfEn = key.split('=')[0];
                    var val = key.split('=')[1];
                    treeUrl = treeUrl.replace("@" + attrKeyOfEn, val);
                    treeTag1 = treeTag1.replace("@" + attrKeyOfEn, val);
                    rootNo = rootNo.replace("@" + attrKeyOfEn, val);
                }
            }

            if (rootNo == "")
                rootNo = "0";

            global.TreeUrl = treeUrl;
            treeUrl = treeUrl.replace("@Key", rootNo);
            treeUrl = treeUrl.replace("@key", rootNo);
            treeUrl = treeUrl.replace("@KEY", rootNo);

            if (treeUrl == "") {
                alert('配置错误:查询数据源，初始化树的数据源不能为空。');
                return;
            }

            // 初始化加载
            var frmEleDBs = new Entities("BP.Sys.FrmEleDBs");
            frmEleDBs.Retrieve("FK_MapData", FK_MapData, "EleID", AttrOfOper, "RefPKVal", oid);
            $.each(frmEleDBs, function (i, o) {
                global.selectedNodes.push({
                    "No": o.Tag1,
                    "Name": o.Tag2
                });
            });

            // search
            $("#TB_Key").on("keyup", function () {
                var keyWord = $(this).val();
                if (keyWord == "") {
                    $('#viewGrid_Panel').hide();
                    $('#tree_Panel').show();
                    return;
                }
                keyWord = replaceAll(keyWord, "'", "");
                
                loadViewGrid(treeTag1,keyWord);
            });

            if (treeUrl.toLowerCase().indexOf("@key") > -1) {
                treeUrl = replaceAll(treeUrl, "@Key", "");
                treeUrl = replaceAll(treeUrl, "@key", "");
                treeUrl = replaceAll(treeUrl, "@KEY", "");
            }

            $('#viewGrid_Panel').hide();
            $('#tree_Panel').show();

            // tree
            loadTree(treeUrl, rootNo, global);
        });

        ///获取已经勾选节点
        function GetCheckNodes() {
            var nodeIds = [];
            var preNo = "";
            var gridPanel = $("#viewGrid_Panel");
            if (gridPanel.is(':hidden')) { //如果列表是隐藏的则获取树控件值
                var checkedNodes = [];
                if (mapExt.ShowCheckBox == true) {
                    checkedNodes = $('#tree').treeview("getChecked");
                } else {
                    checkedNodes = $('#tree').treeview("getSelected");
                }
                $.each(checkedNodes, function (i, node) {
                    if (preNo == "" || preNo != node.id) {
                        preNo = node.id;
                        var item = {};
                        item.No = node.id;
                        item.Name = node.text;
                        Savcceval(global.FK_MapData, global.AttrOfOper, global.oid, node.id, node.text);
                        nodeIds.push(item);
                    }
                });
            } else {
                var selectedRows = $("#viewGrid").bootstrapTable("getSelections");
                $.each(selectedRows, function (i, row) {
                    var item = {};
                    item.No = row.No;
                    item.Name = row.Name;
                    Savcceval(global.FK_MapData, global.AttrOfOper, global.oid, row.No, row.Name);
                    nodeIds.push(item);
                });
            }
            return nodeIds;
        }
        //设置值.
        function Savcceval(fk_mapdata, keyOfEn, oid, val1, val2) {
            var frmEleDB = new Entity("BP.Sys.FrmEleDB");
            frmEleDB.MyPK = keyOfEn + "_" + oid + "_" + val1;
            frmEleDB.FK_MapData = fk_mapdata;
            frmEleDB.EleID = keyOfEn;
            frmEleDB.RefPKVal = oid;
            frmEleDB.Tag1 = val1;
            frmEleDB.Tag2 = val2;
            if (frmEleDB.Update() == 0) {
                frmEleDB.Insert();
            }
        }

        /**
       * 根据字段，参数，查询类型获取JSON数据
       * @param field mapExt需要查询的字段
       * @param paras 参数值
       */
        function GetDataTableByField(field, paras) {

            if (atParas != "")
                paras = atParas + "@Key=" + paras;
            var en = new Entity("BP.Sys.MapExt", mapExt.MyPK);
            var json = en.DoMethodReturnString("GetDataTableByField", field, paras, null, GetQueryString("OID"),null);
            if (json.indexOf("err@") != -1) {
                alert(json);
                return "";
            }
            json = JSON.parse(json);

            return json;
        }
    </script>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12">
                <div class="row">
                    <div class="col-md-9 col-sm-9">
                        <div class="pull-center search search-margin">
                            <input class="form-control" type="text" placeholder="" id="TB_Key" style="width:90%">
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="row row-margin-top">
            <div class="col-md-4 col-sm-4" id="tree_Panel">
                <div id="tree"></div>
            </div>
            <div class="col-md-4 col-sm-4" id="viewGrid_Panel">
                <table id="viewGrid"></table>
            </div>
        </div>
    </div>
</body>
</html>
